package com.ruoyi.pay.controller;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.pay.config.RequestLimit;
import com.ruoyi.pay.domain.Order;
import com.ruoyi.pay.domain.dto.OrderDTO;
import com.ruoyi.pay.service.IOrderService;
import com.ruoyi.pay.service.impl.AliPayService;
import com.ruoyi.system.api.RemoteFileService;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.security.annotation.RequiresPermissions;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 * 
 * @author Larry
 * @date 2024-03-26
 */
@Slf4j
@RestController
public class OrderController extends BaseController
{

    @Autowired
    private IOrderService orderService;

    @Resource
    private AliPayService aliPayService;
    @RequestLimit
    @GetMapping("/test")
    public String test(){
        return "dada";
    }

    @PostMapping("/gen")
    public R<String> add(@RequestBody OrderDTO order)
    {
        return R.ok(aliPayService.genOrder(order));
    }
    @PostMapping("/callBack")
    public String callBack(HttpServletRequest request) throws AlipayApiException {
        // 1:获取支付宝支付成功后回调过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, new String(valueStr.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, "" +
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj3g94Oo4M+1WtZdHTu7CbAjAWBrOHV2RwGKYkUTNs/PuInqwOYJVM9up5CIEyqCpXSV6UjnUx4CqP3Bt2u+CjVFMlQvw89GDlN7lj+yGjtGMzgl996ffa9dsb4/aVUwB2B1fb07lIkJmJguwEQlu6fKXeSr5fH8It0pMJL5wkP07SDPzHy1OUOoUVZW4Qye9jxxzps3DfdUNGqRFtb/DTfB8vV5goMP+QE0nBfLgd/LM79puu/aLOlFhZ/FOXd8TlyVOuokoaxpxjgZnF5xgJgKA8kl+MKb+WR9Xl0iutf51pLne7lJKROBkM/uZcbp8bD04K1W6BZtGW/Y9l9geGQIDAQAB", "utf-8", "RSA2");
        if (!signVerified) {
            log.warn("# 【支付宝回调验签】 验签失败，非法请求");
            return "FAILURE";
        }
        String tradeNo = params.get("trade_no");
        String bodyJson = params.get("body");
        JSONObject bodyJsonObject = JSONObject.parseObject(bodyJson);
        String title = bodyJsonObject.getString("title");
        String orderNum = bodyJsonObject.getString("orderNum");
        String fee = bodyJsonObject.getString("fee");
        log.info("# 支付宝交易号：{} 标题：{},订单号：{}，费用:{}", tradeNo, title, orderNum, fee);
//        orderService.finish(tradeNo, orderNum, fee);
        return "SUCCESS";
    }
    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:order:list")
    @GetMapping("/list")
    public TableDataInfo list(Order order)
    {
        startPage();
        List<Order> list = orderService.selectOrderList(order);
        return getDataTable(list);
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @RequiresPermissions("system:order:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(orderService.selectOrderById(id));
    }

    /**
     * 新增【请填写功能名称】
     */


    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("system:order:edit")
    @PutMapping
    public AjaxResult edit(@RequestBody Order order)
    {
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:order:remove")
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(orderService.deleteOrderByIds(ids));
    }
}
